<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Controller to for user related information
 * 
 * Sample bench Marking
 *    $this->benchmark->mark('login_start'); 
 *    $this->benchmark->mark('login_end'); 
 *    $this->benchmark->elapsed_time('login_start', 'login_end');
 */
class User extends MY_Controller{

    protected  $permission = 'user';
    protected  $page_config = array(
        //'base_url' = 'http://example.com/index.php/test/page/',
        'base_url' => '/admin/lists',
        'total_rows' => 200,
        'per_page' => 20,
        'enable_query_strings'=>TRUE,
        'query_string_segment'=>'ppage',
        
    );
    
    public function __construct() {
        parent::__construct();
        //$this ->page_config['enable_query_string']=true;
        if($this->acl_auth->logged_in() && !$this->session->userdata("user_id")){
            // Annoying why theres user_id in session.
            // I will logout him then.
            $this->redirect('logout');
        }
    }

    public function modelObject($key='login_attempt'){
    }
    
	public function servar(){
        foreach($_SERVER as $key => $v)
            echo '<b>'.$key.'</b> => '.$v."\n<br />";
    }
	public function index()
	{
        if ($this->acl_auth->logged_in()){
            // user already loggedin, put him to the appropriate page.
            if ($this->acl_auth->has_role('admin')){
                $this->redirect('lists'); // Admin must go to admin page.
            }else{
                redirect($this->acl_auth->get_config('landing_page'));
            }
        }

        $this->login();
	}
    
    public function login()
    {
        if ($this->acl_auth->logged_in()){
            if ($this->acl_auth->isPasswordExpired()){
                $this->redirect('logout');
            }

            // user already loggedin, put him to the appropriate page.
            if ($this->acl_auth->has_role('admin')){
                $this->redirect('lists'); // Admin must go to admin page.
            }else{
                redirect($this->acl_auth->get_config('landing_page'));
            }
        }
        
        log_message('debug', 'TimeDate: '.  date('Y-m-d H:i:s',1426164804)
                ." -> ".date('Y-m-d H:i:s')
                ." -> ".date('Y-m-d H:i:s', time())
                );
        $this->enableProfiler();
        $views['_content'] = 'user/login';
        //$data['name']="Winzter143";
        
        $data['login']=true; // Only tells that you are one login page.
        
        // TODO Must by All Post
        //$attempt = $this->session->userdata('login_attempt');

        // Get all locked users.
        $users_locked_json = $this->acl_auth->get_locked_users();
        
        log_message('debug', 'LOCKED USER'. print_r($users_locked_json, 1));
        if ($this->isPost()){
            $email = $this->input->post('txt_email'); // Account name
            
            if(0 && isset($users_locked_json[$email])){
                // @win This section must not run anymore since I already disable the cookie
                // 
                // This will prevent/limit going to database call.
                $data['msg']=$this->acl_auth->get_message('msg_login_attempt');
                $data['disable_login']=true;
                $data['info']=str_replace(array('{max_attemp}','{log_expired}'),
                        array($this->acl_auth->get_config('login_max_attempt'),
                            $this->acl_auth->add_locked_expiration()),
                        $this->acl_auth->get_message('msg_login_attempt_info'));
            }else{
                $pass = $this->input->post('txt_pass');
                $this->session->set_userdata('last_login_user',$email);
                
                if ($email && $pass){
                    // Validate the record

                    $session = array();
                    // TODO Check, if have account to for API.
                    if($this->permission==='admin'){
                        $this->acl_auth->setIsLoggedAdmin(true);
                    }
                    $success = $this->acl_auth->login($email,$pass,false,$session); 

                    if ($success){
                        log_message("info", "Logged-in");
                        $session = $this->session;

                        $data['name'] = $session->userdata('user_email');
                        $firsttime=$session->userdata('logged');
                        
                        $firsttime=$session->userdata('logged');
                        //$passwordExpired=($session->userdata('p_exp')<time());
                        $passwordExpired=$this->acl_auth->isPasswordExpired();

                        if (!$firsttime || $passwordExpired){ // user First time logged-in
                            if ($passwordExpired){
                                log_message('debug','Password already expired need to set new one.');
                                $this->session->set_flashdata('message', $this->acl_auth->get_message("password_expired"));
                            }
                            $this->redirect('changePassword');
                        }
                        if ($this->acl_auth->has_role("admin")){
                            $this->redirect('lists');
                        }else{
                            redirect($this->acl_auth->get_config('landing_page'));
                        }

                        // if Admin
                        // Redirect to desired page for hime
                    }else{
                        $errors = $this->acl_auth->errors();
                        $data['msg']=$errors[0]; // @TODO I must read all errors

                        //$attempt = $this->session->userdata(strtolower($email));
                        $json_attempt = $this->session->userdata(strtolower($email));
                        if ($json_attempt){
                            $json_attempt = $json_attempt?json_decode($json_attempt, true):array();
                            $attempt = isset($json_attempt['att'])?$json_attempt['att']:1;
                            $exp = isset($json_attempt['exp'])?$json_attempt['exp']:1;

                            $max_attempt = $this->acl_auth->get_config('login_max_attempt');
                            log_message('debug', __METHOD__.' -> Log {'.$email .'} Attempt('.$attempt.' > '.$this->acl_auth->get_config('login_max_attempt').')');
                            log_message('debug', __METHOD__.' -> Log {'.$email .'} Attempt('.date('y-m-d H:i:s',$exp).'>'.date('y-m-d H:i:s',time()).')');
                            if (($attempt >= $max_attempt) && ($exp > time())){
                                // user locked

                                $this->load->model('user_model');
                                $data['disable_login']=true;
                                $data['info']=str_replace(array('{max_attemp}','{log_expired}'),
                                    array($max_attempt,
                                        $this->acl_auth->add_locked_expiration('locked_attempt_exp')),
                                    $this->acl_auth->get_message('msg_login_attempt_info'));

                                // Locked the User
                                $this->user_model->locked_user($this->acl_auth->get_user_id());

//                                $cookie = array(
//                                    'name'   => 't_ul', // json array of locked users
//                                    'value'  => $this->acl_auth->add_locked_user($email),
//                                    'expire' => '86500',
//                                    //'domain' => '.some-domain.com',
//                                    'path'   => '/',
//                                    //'prefix' => 'myprefix_',
//                                    //'secure' => TRUE
//                                );
//                                $this->input->set_cookie($cookie);
                            }
                        }else{ // if ($json_attempt){
                            // Nothing to do.
                            log_message('error','No valid user.. check your fact sheet of users. :)');
                        }
                    }

                }
            }
        }// if ($this->isPost()){

        // Render the Login Palge
        // Add your child template here
        $views['_header'] = 'user/header';

        $this->benchmark->mark('login_start'); 
        $this->template->load('user/main', $views, $data);
        $this->benchmark->mark('login_end');         
        
    }
    
    
    public function lists()
    {
        if ($this->acl_auth->logged_in() && $this->acl_auth->isPasswordExpired()){
            $this->redirect('logout');
        }

        $this->acl_auth->restrict_access('admin');
        $this->enableProfiler();
        
        
        $views['_tabs'] = 'user/tabs';
        $views['_userform'] = 'user/user_form';
        $views['_content'] = 'user/lists';
        $this->load->model('user_model');

        $usermodel = $this->user_model;
        // search function?? clear the pointer index(inshort pager) 
        // and sorting order
        
        // Get  the search params. Initially from Cookies
        $searchinfo = array(
//            'page' => '',
//            'field'=> '', // Field To sort
//            'dir'=> '', // ASC/DESC
            'page' => $this->input->get('per_page',1),
            'field'=> $this->input->get('field',1), // Field To sort
            'dir'=> $this->input->get('dir',1), // ASC/DESC
            'account_name'=>'',
            'lname'=>'',
            'fname'=>'',
            'store_name'=>'',
            );
            
        $searchable = array(
            'account_name' => '',
            'lname' =>  '',
            'fname' =>  '',
            'store_name' =>  '',
        );
        log_message('debug', 'INIT: '.json_encode($searchinfo));
        
        $searchinfos = $this->input->cookie('t_searchinfo');
        if ($searchinfos){
            log_message('debug', 'Cookie: '.$searchinfos);
            $searchinfos = json_decode($searchinfos, true);
            if ($searchinfos && is_array($searchinfos)){
                foreach ($searchinfos as $field => $value){
                    // TODO, DO I need to validate the fields
                    if (isset($searchinfo[$field])){
                         if(($field == 'page')&&(!$searchinfo[$field])){
                             $searchinfo[$field] = 0; // Dont everride instead put zero
                         }elseif(!$searchinfo[$field]){
                            $searchinfo[$field] = $value; // assign the from from cookie
                        }
                    }
                    if (isset($searchable[$field]))
                        $searchable[$field] = $value;
                }
            }
        }

        if (!$searchinfo['dir']) $searchinfo['dir'] = 'ASC';
        if (!$searchinfo['field'])$searchinfo['field']='account_name';
        
        
        // Setup the sorting datas
        $usermodel->set_order_field($searchinfo['field'])
                ->set_order_dir($searchinfo['dir']);

        
        if ($this->isPost() && $this->input->post('btn_search')){
            $searchable = array(
                'account_name' =>  $this->input->post('account_name'),
                'lname' =>  $this->input->post('lname'),
                'fname' =>  $this->input->post('fname'),
                'store_name' =>  $this->input->post('store_name'),
            );
            foreach ($searchable as $field => $value) {
                $searchinfo[$field] = $value;
            }
            
            $searchinfo['page']=0; // reset.
            $searchinfo['field']=null; // reset.
            $searchinfo['dir']=null; // reset.
        }

        
        log_message('error', json_encode($searchinfo));
        // Save search info on cookie.
        $cookie = array(
            'name'   => 'searchinfo',
            'value'  => json_encode($searchinfo),
            //'expire' => '1800', // 30 mins
            'expire' => '86500',// 30 mins
            //'domain' => '.globe.com.ph',
            'path'   => '/',
            'prefix' => 't_',
            //'secure' => TRUE
        );
        $this->input->set_cookie($cookie);
        

        
        
        log_message('debug', 'Searchable:::==>> '.print_r($searchable, 1));
        $usermodel->set_searchable_fields($searchable);
        $data['users']= $usermodel->get_all_user($searchinfo['page'], $this->page_config['per_page']);
        $data['stores']=$this->user_model->get_all_store();
        //$data['stores']=array('Mega','Rob Galeer');
        
        $data['title']='List of Users';
        $data['account_name']= $this->session->userdata('account_name');;
        if ($datas = $this->session->flashdata('datas')){
            $data['datas'] = json_decode($datas, true);
        }
        
        if ($errors = $this->session->flashdata('errors')){
            $data['errors'] = json_decode($errors, true);
        }
        $this->load->library('pagination');
//        log_message('debug', print_r($this->page_config, 1));
        $config=array('base_url' => base_url('').'admin/lists?field='.$searchinfo['field'].'&dir='.$searchinfo['dir'],
                    'total_rows' => $this->user_model->get_count_by_search_field(),
                    'per_page' => $this->page_config['per_page'],
            );

        $this->pagination->initialize($config);
        $data['pages']= $this->pagination->create_links();
        $data['searchinfo']=$searchinfo;
        $data['_dir']=$searchinfo['dir'];
        $data['_field']=$searchinfo['field'];
        $data['_page']=$searchinfo['page'];
        $data['_status']=array(1=>'Active', 0=>'Inactive');
        $data['_error']=$this->session->flashdata('error');
        $data['_success']=$this->session->flashdata('success');
         
        $this->template->load('user/admin', $views, $data);
        
    }
    

    /**
     * Delete user
     * 
     * @param int $id
     */
    public function delete($id=""){
        //$this->acl_auth->restrict_access('admin');
        if ($this->acl_auth->delete($id)){
            $msg = $this->acl_auth->messages();
            $this->session->set_flashdata('success', $msg[0]);
        }else{
           $this->session->set_flashdata('error', "Failed to delete account.");
        }
        
        $this->redirect('lists');        
    }
    
    
    
    /**
     * 
     * Change Password
     */
    public function changePassword()
    {
        $this->acl_auth->restrict_access('logged_in');
        $this->enableProfiler();
        
        $data = array();
        $views = array();
        if ($this->isPost()){
            //redirect('user/changePassword');return;
            // Update user password
            //
            $pass = $this->input->post('password');
            $vpass = $this->input->post('vpassword');
            $accountName = $this->session->userdata("account_name");
            if($accountName != $vpass){
                if (trim($vpass) < $this->acl_auth->get_config('pass_len')){
                    $this->session->set_flashdata('error', "Password must be at least 8 characters.");
                    redirect('user/changePassword'); // Return him to new password nomination.
                }else{
                    if ($pass==$vpass)
                    {
                        if($this->acl_auth->changePassword($pass)){
                            if($this->acl_auth->has_role("admin")){
                                $this->redirect('lists');
                            }else{
                                redirect($this->acl_auth->get_config('landing_page'));
                            }
                        }
                        $views['_content'] = 'user/changepassword';
                        $data['title']='Change Password';
                    }else{
                        // This section must not execute since password matches validate
                        // Already implemented on JS. But since many 9GAG people,
                        // I better made failed over scenario.
                        redirect('user/changePassword'); // Return him to new password nomination.
                    }
                }
            }else{
                $this->session->set_flashdata('error', $this->acl_auth->get_message("user_password_same"));
                redirect('user/changePassword'); // Return him to new password nomination.
            }
            
            // if success. please  login again
        }else{
            // View change Passwword template            
            $data['title']='Change Password';
            $data['account_name'] = $this->session->userdata('user_account_name');
            $data['fmessage'] = $this->session->flashdata('message');
            if (!$data['fmessage']){
                $data['fmessage'] = $this->session->flashdata('error');
            }
            
            $views['_content'] = 'user/changepassword';
            $data['login']=true; // Only tells that you are one login page.

        }
        $this->template->load('user/main', $views, $data);
        
    }
    
    
    /**
     * 
     * @param type $email
     * @param type $token
     */
    public function resetPassword($account_name=null, $token = null)
    {

//        $this->acl_auth->restrict_access('logged_in');
        //exit($this->session->flashdata('message'));
        $views = array();
        $data = array();
        $data['title']='Password reset';
        $views['_content'] = 'user/resetpassword';
        
        
        //$data['fmessage']=$this->session->flashdata('message');
        
        log_message('debug', "$account_name=null, $token = null");
        $account_name = ($account_name)? $account_name: $this->input->post('account_name');
        $token = ($token)?$token:$this->input->post('token');
        
        if ($this->isPost() && ($token || $account_name))
        {
            
            log_message('debug', 'Posted ot have token');
            if ($token){
                // Save The new password
                $password = $this->input->post('password');
                log_message("debug", "$account_name <--> $token <--> $password ");
                $setnewpass = $this->acl_auth-> set_new_password(
                        $account_name,
                        $token,
                        $password);
                if ($setnewpass){
                    $this->redirect('login');
                }else{
                    $data['msgs']=$this->acl_auth->errors();
                    //$this->session->set_flashdata('message', $data['msgs']);
                    $data['viewreset'] = true;
                }
            }else{
                //$account_name=$account_name?$account_name:$this->input->post('account_name');
                // Send the token
                if ($token){
                    $data['success']=$data['viewreset']=true; // tell to view the reset password form
                    $data['token']=  urldecode($token);
                    $data['account_name']=$account_name;
                }elseif ($email = $this->acl_auth->send_password_reset($account_name)){
                    $data['title']='Please check you email for reset code.';
                    $data['account_name']=$account_name;                    
                    $data['msgs']=  str_replace('{email}', $email , $this->acl_auth->get_config('reset_message_success'));
                    //$data['msgs']="Please check you email for token/reset code.";
                    //$this->session->set_flashdata('message', $data['msgs']);
                    $data['success']=$data['viewreset']=true; // tell to view the reset password form
                }else{
                    $data['msgs']=$this->acl_auth->errors();
                    //$this->session->set_flashdata('message', $data['msgs']);
                }
            }
        }else{
            log_message('debug', 'reset password form');
            $data['title']='Password reset';
            $data['fmessage']=$this->session->flashdata('message');
        }
        
        //$this->benchmark->mark('login_start'); 
        $this->template->load('user/main', $views, $data);

    }
    
    
    /**
     * Logout
     */
    public function logout(){
        $success = $this->acl_auth->logout();
        
        if ($success){
            $this->deleteCookies();
            $this->redirect('login');
        }else{
            $this->redirect('lists');
        }
    }// logout()
    
    protected function redirect($path){
        redirect('user/'.$path);
    }

    protected function deleteCookies($isAdmin = false){
        // Delete Tiangge Cookies
        $cookies = array('address','area','bday','choosePromo','commitmentBox',
            'commitmentMonths','current_pos','discounted','eadd','gadget','gadgetid',
            'globestore','globestoreid','gadgetid','imgsrc','mobtel','months',
            'nname','othercont','postalcode','postalIds','price','promo','promoDesc',
            'promoprice','province','rebateamt','sku','sumname',
            'totalcash','totalrebate','town','username',
            'validity','temp_mobtel','mode','usertype','storehours',
            'storeLong','storeLat','planprice','loc','globestoreAddress',
            'globestoreAddress','expiration','region',
            //'mt_client',
            );
        if (!$isAdmin){
            // Delete All Cookie that was set by JR
            // Sorry to GoSakto If you I get delete you cookies. :)
            foreach($cookies as $v){
                if (isset($_COOKIE[$v]))delete_cookie($v);
            }

            // Delete All Tiannge Cookies
            foreach($_COOKIE as $k => $v){
                if(preg_match('/Tiangge/i', $k))delete_cookie($k);
            }
        }
    }

    public function unauthorized(){
        $views = array();
        $data = array();
        $data['title']='Forbidden';
        $views['_content'] = 'user/unauthorized';
        $this->template->load('user/main', $views, $data);

    }
//    public function testflash(){
//        $this->session->set_flashdata('message', "Password expired");
//        $this->redirect('changePassword');
//        //$this->redirect('getflash');
//
//    }
//    public function getflash(){
//        echo $this->session->flashdata('message');
//        
//
//    }

    
} // User class
